import React, { useRef, useEffect } from "react";
import PropTypes from "prop-types";
import Button from "../Button";

import './index.scss'


export default function Modal(props) {

    const modalRef = useRef()

    useEffect(() => {
        const modalEl = modalRef.current
        if (props.visible) {
            modalEl.style.zIndex = '100'
            modalEl.classList.add('active')

            modalEl.addEventListener('transitionend', () => {
                if (!modalEl.classList.contains('active')) {
                    modalEl.style.zIndex = '-1'
                }
            })
        } else {
            modalEl.classList.remove('active')
        }

    }, [props.visible])

    return (
        <div className={ 'modal-warp' } ref={ modalRef } >
            <div className={ 'modal-mask' } />
            <div className={ 'modal-container' }>
                <div className={ 'modal-header' }>
                    <h1 className={ 'modal-title' }>{ props.title }</h1>
                    <span className={ 'icon-remove modal-close' } onClick={ props.cancel } />
                </div>
                <div className={ 'modal-main' }>{ props.render() }</div>
                <div className={ 'modal-btn' }>
                    <Button style={ {marginRight: '20px', marginLeft: 'auto'} }
                            size={ 'middle' }
                            plain={ true }
                            onClick={ props.cancel }
                    >
                        取消
                    </Button>
                    <Button size={ 'middle' } onClick={ props.submit }>
                        确定
                    </Button>
                </div>
            </div>
        </div>
    )
}

Modal.propTypes = {
    style: PropTypes.object,
    className: PropTypes.string,
    visible: PropTypes.bool,
    title: PropTypes.string,
    render: PropTypes.func,
    submit: PropTypes.func,
    cancel: PropTypes.func
}

Modal.defaultProps = {
    style: {},
    className: '',
    visible: false,
    title: '标题',
    render: () => (<>{'内容'}</>),
    submit: () => {},
    cancel: () => {}
}